package com.flying.flyingchessgame.controller;

import com.flying.flyingchessgame.dto.request.LoginRequest;
import com.flying.flyingchessgame.dto.request.RegisterRequest;
import com.flying.flyingchessgame.dto.response.JwtResponse;
import com.flying.flyingchessgame.dto.response.MessageResponse;
import com.flying.flyingchessgame.entity.User;
import com.flying.flyingchessgame.security.jwt.JwtUtils;
import com.flying.flyingchessgame.security.service.UserDetailsImpl;
import com.flying.flyingchessgame.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 认证控制器
 * <p>
 * 处理用户认证相关的请求，包括登录和注册。
 * </p>
 * 
 * @author flying-chess
 * @version 1.0
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);
    
    /**
     * 认证管理器
     */
    @Autowired
    AuthenticationManager authenticationManager;

    /**
     * 用户服务
     */
    @Autowired
    UserService userService;

    /**
     * JWT工具类
     */
    @Autowired
    JwtUtils jwtUtils;

    /**
     * 处理用户登录请求
     * <p>
     * 验证用户凭证，生成JWT令牌，并返回用户信息。
     * </p>
     *
     * @param loginRequest 登录请求参数
     * @return 包含JWT令牌和用户信息的响应
     */
    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
        logger.info("用户登录请求: {}", loginRequest.getUsername());

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

        SecurityContextHolder.getContext().setAuthentication(authentication);
        String jwt = jwtUtils.generateJwtToken(authentication);
        
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        logger.info("用户登录成功: {}", userDetails.getUsername());
        
        return ResponseEntity.ok(new JwtResponse(jwt,
                                                 userDetails.getId(), 
                                                 userDetails.getUsername(), 
                                                 userDetails.getEmail()));
    }

    /**
     * 处理用户注册请求
     * <p>
     * 验证用户信息，创建新用户，并返回成功消息。
     * </p>
     *
     * @param registerRequest 注册请求参数
     * @return 注册结果消息
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@Valid @RequestBody RegisterRequest registerRequest) {
        logger.info("用户注册请求: {}", registerRequest.getUsername());
        
        if (userService.checkUsernameExists(registerRequest.getUsername())) {
            logger.warn("注册失败: 用户名 {} 已被使用", registerRequest.getUsername());
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误: 用户名已被使用!"));
        }

        if (registerRequest.getEmail() != null && !registerRequest.getEmail().isEmpty() 
                && userService.checkEmailExists(registerRequest.getEmail())) {
            logger.warn("注册失败: 邮箱 {} 已被使用", registerRequest.getEmail());
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误: 邮箱已被使用!"));
        }

        // 创建新用户
        User user = userService.saveUser(
                registerRequest.getUsername(),
                registerRequest.getPassword(),
                registerRequest.getEmail());
                
        logger.info("用户注册成功: {}", user.getUsername());

        return ResponseEntity.ok(new MessageResponse("用户注册成功!"));
    }
} 